package com.asset.service.impl;

import com.asset.mapper.AssetDeprMapper;
import com.asset.mapper.AssetMapper;
import com.asset.pojo.Asset;
import com.asset.pojo.AssetDepreciation;
import com.asset.service.DepreciationService;
import com.asset.util.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 资产折旧管理
 * @author 11725
 */
@Service
public class DepreciationServiceImpl implements DepreciationService {

    @Resource
    private AssetDeprMapper assetDeprMapper;

    @Resource
    private AssetMapper assetMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insert(AssetDepreciation record) {
        assetDeprMapper.insertSelective(record);
    }

    @Override
    public PageResult<AssetDepreciation> selectByPage(Integer page, Integer rows, Date date) {
        PageHelper.startPage(page, rows);

        Example example = new Example(AssetDepreciation.class);
        Example.Criteria criteria = example.createCriteria();

        if (date != null) {
            Integer year, month;
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            year = calendar.get(Calendar.YEAR);
            month = calendar.get(Calendar.MONTH);

            criteria.andCondition("year(depr_date) = ", year);
            criteria.andCondition("month(depr_date) = ", month);
        }

        List<AssetDepreciation> list = assetDeprMapper.selectByExample(example);

        Set<Long> set = list.stream().map(AssetDepreciation::getAssetId).collect(Collectors.toSet());
        List<Asset> assets = assetMapper.selectByIdList(new ArrayList<>(set));
        Map<Long, Asset> map = assets.stream().collect(Collectors.toMap(Asset::getId, e -> e));

        for (AssetDepreciation e : list) {
            e.setAsset(map.get(e.getAssetId()));
        }

        PageInfo<AssetDepreciation> info = new PageInfo<>(list);

        return new PageResult<>(info.getTotal(), list);
    }
}
